import { acceptHMRUpdate, defineStore } from "pinia";
import type {LoginType} from "~/interfaces";
import {ADMIN, BACKEND} from "~/const/LeftBarNav";

export const useLoginStore = defineStore("login", () => {
    const loginType=ref();
    const navs=ref([]);
    const setNavs=(value:any)=>navs.value=value;
    const setLoginType=(login:LoginType)=>loginType.value=login
    const isAdmin=ref(false);
    const setIsAdmin=(value:boolean)=>isAdmin.value=value;
    const visible=ref(false);
    const setVisible=(value:boolean)=>visible.value=value;
    const token=ref('');
    const setToken=(value:string)=>{
        token.value=value;
    }
    const info=ref({});
    const setInfo=(value:any)=>{
        info.value=value
        if(value.admin_id){
            setNavs(BACKEND);
        }else if(value.id){
            setNavs(ADMIN);
        }else{
            setNavs([]);
        }
    };
    const isSecret=ref(false);
    const setSecret=(value:boolean)=>isSecret.value=value;
    const toggleIsSecret=()=>isSecret.value=!isSecret.value;
    const route=useRoute();
    const router=useRouter();
    const loginOut=()=>{
        setToken('');
        setInfo({});
        setIsAdmin(false);
        const tag=useTagsStore();
        tag.clearTags();
        if(route.path!='/index.html'){
            router.push('/index.html')
        }
    }
    const refreshInfo=async ()=>{
        if(token.value&&!isAdmin.value){
            const {data,code} = await useGet('/user/info');
            if(code==200){
                setInfo(data);
            }
        }
    }

    return {
        loginType,
        setLoginType,
        visible,
        setVisible,
        token,
        setToken,
        info,
        setInfo,
        isSecret,
        setSecret,
        loginOut,
        toggleIsSecret,
        refreshInfo,
        isAdmin,
        setIsAdmin,
        navs,
    };
},{persist:true});

if (import.meta.hot){
    import.meta.hot.accept(acceptHMRUpdate(useLoginStore, import.meta.hot));
}